#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <ctype.h>
 
#define BACKLOG          13     /*令listen最大监听数为13*/
#define PORT            8888    /*监听8888号端口*/
#define THRESHOLD		28      /*温度阈值*/

int main(int argc,char *argv[])
{
        int                     fd = -1;
        int                     client_fd = -1;
        int                     rv = -1;
        struct sockaddr_in      server_addr;
        struct sockaddr_in      client_addr;
        socklen_t               client_len = sizeof(client_addr);
        char                    buf[1024];
 
        if((fd=socket(AF_INET,SOCK_STREAM,0))<0)
        {
                printf("Socket failure:%s\n",strerror(errno));
        }
 
        memset(&server_addr,0,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(PORT);
        server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        if((bind(fd,(struct sockaddr *)&server_addr,sizeof(server_addr)))<0)
        {
                printf("bind failure:%s\n",strerror(errno));
                return -2;
        }
 
        listen(fd,BACKLOG);
        printf("\nWaitting for client...\n");
 
 
        if((client_fd=accept(fd,(struct sockaddr *)&client_addr,&client_len))<0)
        {
                printf("Accept failure:%s\n",strerror(errno));
                return -3;
        }
        printf("Connected with client [%d]\n",client_fd);
        while(1)
        {
 
                memset(&buf,0,sizeof(buf));
 
                if((rv=read(client_fd,buf,sizeof(buf))) <= 0)
                {
                        printf("Read failure or get disconnect:%s\n",strerror(errno));
                        return -4;
                }
 
                printf("read %d Byte data from client [%d] :%s\n",rv,client_fd,buf);
				
				// 温度报警功能
				float temp = atof(buf);

				if (temp > THRESHOLD) // 设置温度阈值
				{
					printf("Alarm: Temperature exceeds threshold!\n");

					// 向客户端发送报警信号
					if (write(client_fd, "Alarm", strlen("Alarm")) < 0) {
						printf("Write failure:%s\n", strerror(errno));
						return -5;
					}
					FILE *fp;
					fp = fdopen(client_fd,"r+");  //提取文件描述符的FILE流
					fflush(fp);
				}
 
 
        }
 
        close(client_fd);
        close(fd);
 
}